import axios, { type InternalAxiosRequestConfig } from "axios";
import { showFailToast } from "vant";

const instance = axios.create({
  baseURL: "https://meikou-api.itheima.net",
  timeout: 10000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 注入token
    const user = pmm.getUser();
    if (user.token) {
      // 注入token
      config.headers.Authorization = `Bearer ${user.token}`;
    } else {
      showFailToast("应用认证失败");
      return Promise.reject(new Error("应用认证失败"));
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code === "1") {
      return res.result;
    }
    return Promise.reject(new Error(res.msg));
  },
  (error) => {
    showFailToast({
      message: error.response?.data?.msg || "请求异常",
      duration: 5000
    })
    Promise.reject(error)
  });

export class RequestAxios {
  static get<T>(url: string, params?: object) {
    return instance.get<null, T>(url, {
      params,
    });
  }
  static post<T>(url: string, data?: object) {
    return instance.post<null, T>(url, data);
  }
  static put<T>(url: string, data?: object) {
    return instance.put<null, T>(url, data);
  }
  static delete<T>(url: string, params?: object) {
    return instance.delete<null, T>(url, {
      params,
    });
  }
  static uploadFile<T>(url: string, data?: object) {
    return instance.post<null, T>(url, data, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  }
}
